<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue'
import { useMainStore } from '@/store/index'
import * as echarts from 'echarts/core'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, RadarChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { Back, Download } from '@element-plus/icons-vue'
import { getCakeStatistics,getMonthStatistics } from '@/api/road/index'
import downloade from "@/api/downloade"

// 注册必要的组件
use([
  CanvasRenderer,
  PieChart,
  RadarChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const store = useMainStore()
const year = ref('2025')
const totalDefects = ref(0)

// 导出统计数据
const exportStatistics = () => {
  downloade.getExportStatistics({
    roadName: 'S229', // 使用当前道路编码
  })
}

// 计算总数
const calculateTotal = (data) => {
  return data.reduce((sum, item) => sum + item.value, 0)
}

// 关闭表单
const closeForm = () => {
  store.openDefectForm()
}

// 新配色方案
const colors = {
  primary: '#1A3A6F',    // 藏蓝色 - 主色
  secondary: '#005BAA',  // 科技蓝 - 辅助色
  background: '#F5F5F5', // 浅灰色 - 背景
  text: '#333333',       // 深灰色 - 文字
  warning: '#FF6B35',    // 橙色 - 警示
  danger: '#D32F2F',     // 红色 - 危险
  success: '#4CAF50',    // 绿色 - 成功
  highlight: '#E1F5FE',  // 浅蓝 - 高亮
  accent: '#C0C0C0'      // 金属银 - 点缀
}

// 饼图配置
const chartOption = ref({
  backgroundColor: 'transparent',
  tooltip: {
    confine: false,
    position: 'top',
    extraCssText: 'z-index: 1000; box-shadow: 0 2px 12px rgba(0,0,0,0.1); border-radius: 4px;'
  },
  color: [
    colors.primary,
    colors.secondary, 
    colors.warning,
    colors.success,
    '#8E44AD'  // 紫色
  ],
  title: {
    show: false
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    top: 'center',
    textStyle: {
      color: '#fff',
      fontSize: 12
    },
    itemWidth: 15,
    itemHeight: 10,
    itemGap: 10
  },
  series: [
    {
      name: '缺陷类型',
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['60%', '50%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 6,
        borderColor: 'rgba(255, 255, 255, 0.2)',
        borderWidth: 1,
        shadowBlur: 10,
        shadowColor: 'rgba(0, 0, 0, 0.2)'
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '16',
          fontWeight: 'bold',
          color: '#fff'
        },
        itemStyle: {
          shadowBlur: 20,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      labelLine: {
        show: false
      },
      data: [
        { value: 1048, name: '路基' },
        { value: 735, name: '沥青路面' },
        { value: 580, name: '水泥路面' },
        { value: 484, name: '沿线设施' },
        { value: 300, name: '保洁' }
      ]
    }
  ]
})

// 添加中心文本显示总数
const updateChartWithTotal = () => {
  const total = calculateTotal(chartOption.value.series[0].data)
  totalDefects.value = total
  
  // 使用类型断言解决类型检查问题
  chartOption.value.series[0].label = {
    show: true,
    position: 'center',
    formatter: '{total|' + total + '}\n{name|总数}',
    rich: {
      total: {
        fontSize: 24,
        fontWeight: 'bold',
        color: '#fff',
        padding: [0, 0, 5, 0],
        textShadow: '0 1px 3px rgba(0, 0, 0, 0.3)'
      },
      name: {
        fontSize: 14,
        color: 'rgba(255, 255, 255, 0.7)',
        padding: [5, 0, 0, 0]
      }
    }
  } as any
}

// 雷达图配置
const radarOption = ref({
  backgroundColor: 'transparent',
  tooltip: {
    confine: false,
    position: 'top',
    extraCssText: 'z-index: 1000; box-shadow: 0 2px 12px rgba(0,0,0,0.1); border-radius: 4px;'
  },
  radar: {
    indicator: [
      { name: '超时率', max: 100 },
      { name: '派单率', max: 100 },
      { name: '维修率', max: 100 },
      { name: '灌缝率', max: 100 }
    ],
    shape: 'circle',
    radius: '70%',
    center: ['50%', '50%'],
    startAngle: 45,
    splitLine: { 
      lineStyle: { 
        color: 'rgba(255, 255, 255, 0.3)',
        width: 1
      } 
    },
    splitArea: { 
      show: true,
      areaStyle: { 
        color: ['rgba(255, 255, 255, 0.05)', 'rgba(255, 255, 255, 0.1)'] 
      } 
    },
    axisLine: { 
      lineStyle: { 
        color: 'rgba(255, 255, 255, 0.5)',
        width: 1
      } 
    },
    name: { 
      color: '#fff',
      fontSize: 12,
      padding: [3, 5],
      textBorderColor: 'rgba(0,0,0,0.3)',
      textBorderWidth: 2,
      backgroundColor: 'rgba(26, 58, 111, 0.7)',
      borderRadius: 3,
      formatter: (text, idx) => {
        return text;
      },
      rich: {
        value: {
          color: '#fff',
          fontSize: 12,
          align: 'center'
        }
      }
    },
    axisName: {
      show: true
    }
  },
  series: [{
    name: '维修指数',
    type: 'radar',
    data: [
      {
        value: [80, 90, 70, 20],
        name: '维修指数',
        areaStyle: { 
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(0, 91, 170, 0.8)' },
            { offset: 1, color: 'rgba(0, 91, 170, 0.2)' }
          ]),
          opacity: 0.6
        },
        lineStyle: { 
          color: colors.secondary,
          width: 2,
          shadowBlur: 5,
          shadowColor: 'rgba(0, 91, 170, 0.3)'
        },
        symbol: 'circle',
        symbolSize: 6,
        itemStyle: { 
          color: colors.secondary,
          borderColor: '#fff',
          borderWidth: 1,
          shadowBlur: 5,
          shadowColor: 'rgba(0, 0, 0, 0.3)'
        }
      }
    ]
  }]
})

// 柱状图配置
const barOption = ref({
  backgroundColor: 'transparent',
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    },
    confine: false,
    position: 'top',
    extraCssText: 'z-index: 1000; box-shadow: 0 2px 12px rgba(0,0,0,0.1); border-radius: 4px;'
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    top: '15%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: ['2020', '2021', '2022', '2023', '2024', '2025'],
    axisLine: {
      lineStyle: {
        color: 'rgba(255, 255, 255, 0.3)'
      }
    },
    axisLabel: {
      color: '#fff',
      fontSize: 12
    }
  },
  yAxis: {
    type: 'value',
    name: '缺陷数量',
    nameTextStyle: {
      color: 'rgba(255, 255, 255, 0.7)',
      fontSize: 12
    },
    axisLine: {
      show: true,
      lineStyle: {
        color: 'rgba(255, 255, 255, 0.3)'
      }
    },
    axisLabel: {
      color: '#fff',
      fontSize: 12
    },
    splitLine: {
      lineStyle: {
        color: 'rgba(255, 255, 255, 0.1)'
      }
    }
  },
  series: [
    {
      name: '缺陷数量',
      type: 'bar',
      data: [320, 420, 560, 780, 890, 1024],
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(0, 91, 170, 0.9)' },
          { offset: 1, color: 'rgba(26, 58, 111, 0.7)' }
        ]),
        borderRadius: [4, 4, 0, 0]
      },
      emphasis: {
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(0, 91, 170, 1)' },
            { offset: 1, color: 'rgba(26, 58, 111, 0.9)' }
          ])
        }
      }
    }
  ]
})

// 模拟数据更新
const updateChartData = async () => {
   await getCakeStatistics('S229').then(res => {
    let newData = []
    res.data.statisticsVos.forEach(item => {
      newData.push({value: item.totalDefectType,name: item.defectType})
    })
    chartOption.value.series[0].data = newData
    // 更新图表中心的总数显示
    updateChartWithTotal()
  })

  await getMonthStatistics('S229').then(res => {
    let newData = []
    let xAxisData = []
    
    res.data.forEach(item => {
      newData.push(item.total)
      xAxisData.push(item.dateMonth)
    })
    
    // 更新柱状图配置
    barOption.value.xAxis.data = xAxisData
    barOption.value.series[0].data = newData
  })
}

// 更新模拟数据
const updateBarChartData = () => {
  // 此功能由API调用替代，不再使用模拟数据
  console.log('不再使用模拟数据')
}

onMounted(async() => {
  // 组件挂载时，如果表单已经是打开状态，立即获取数据
  if (store.isOpenStatistics) {
    await updateChartData()
    // updateBarChartData() // 不再调用模拟数据方法
  }
})

// 监听表单显示状态，当表单被打开时自动获取最新数据
watch(() => store.isOpenStatistics, async (newValue) => {
  if (newValue) {
    await updateChartData()
    // updateBarChartData() // 不再调用模拟数据方法
  }
}, { immediate: true })

// 监听更新标志，当需要更新时获取最新数据
watch(() => store.shouldUpdateStatistics, async (shouldUpdate) => {
  if (shouldUpdate && store.isOpenStatistics) {
    await updateChartData()
    // updateBarChartData() // 不再调用模拟数据方法
    // 标记数据已更新
    store.markStatisticsUpdated()
  }
})
</script>

<template>
<div :class="store.isOpenStatistics ? 'statisticsFormBox show' : 'statisticsFormBox'">
  <div class="content-wrapper">
    <div class="title">
      <h3>分类统计</h3>
      <div class="title-actions">
        
        <el-button type="primary" :icon="Back" @click="closeForm" class="action-btn">返回</el-button>
      </div>
    </div>
    <div class="FormBox">
      <div class="box1">
        <!-- 巡查指数卡片 -->
        <el-card class="index-card">
          <div class="card-header">
            <span>巡查指数</span>
            <el-date-picker v-model="year" type="year" placeholder="选择年份" size="small" style="width: 100px;" />
          </div>
          <el-row :gutter="16" class="index-row">
            <el-col :span="12">
              <div class="index-item">
                <i class="iconfont icon-find"></i>
                <div class="index-value">1524</div>
                <div class="index-label">发现总数</div>
              </div>
            </el-col>

            <el-col :span="12">
              <div class="index-item">
                <i class="iconfont icon-frequency"></i>
                <div class="index-value">42</div>
                <div class="index-label">巡查次数</div>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="16" class="index-row">
            <el-col :span="12">
              <div class="index-item">
                <i class="iconfont icon-road"></i>
                <div class="index-value">1256</div>
                <div class="index-label">总里程km</div>
              </div>
            </el-col>

            <el-col :span="12">
              <div class="index-item">
                <i class="iconfont icon-cover"></i>
                <div class="index-value">851</div>
                <div class="index-label">覆盖里程km</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
        
        <!-- 缺陷分布饼图 -->
        <el-card class="index-card">
          <div class="card-header">
            <span>缺陷类型分布</span>
            <el-button type="primary" :icon="Download" @click="exportStatistics" class="action-btn">导出</el-button>
          </div>
          <div class="chart-container">
            <v-chart class="chart" :option="chartOption" autoresize />
          </div>
        </el-card>
        

      </div>
      
      <div class="box1">
        <!-- 维修指数卡片 -->
        <el-card class="index-card">
          <div class="card-header">
            <span>维修指数</span>
          </div>
          <el-row :gutter="16" class="index-row">
            <el-col :span="8">
              <div class="repair-index-list">
                <div class="repair-index-item">
                  <div class="repair-index-value">1302</div>
                  <div class="repair-index-label">待维修总数</div>
                </div>
                <div class="repair-index-item">
                  <div class="repair-index-value">8</div>
                  <div class="repair-index-label">已维修总数</div>
                </div>
                <div class="repair-index-item">
                  <div class="repair-index-value">20</div>
                  <div class="repair-index-label">混编率</div>
                </div>
              </div>
            </el-col>
            <el-col :span="16">
              <div class="radar-container">
                <v-chart class="radar-chart" :option="radarOption" autoresize />
              </div>
            </el-col>
          </el-row>
        </el-card>
                <!-- 年度缺陷数量柱状图 -->
        <el-card class="index-card">
          <div class="card-header">
            <span>年度缺陷数量统计</span>
          </div>
          <div class="chart-container">
            <v-chart class="chart" :option="barOption" autoresize />
          </div>
        </el-card>
      </div>
    </div>
  </div>
</div>
</template>

<style scoped>
.statisticsFormBox {
  box-sizing: border-box;
  position: fixed;
  left: -100%;
  top: 0;
  width: 850px;
  height: 100vh;
  background: rgba(19, 32, 57, 0.9);
  transition: all .8s cubic-bezier(0.68, -0.55, 0.265, 1.55);
  padding: 20px;
  z-index: 99;
  color: #fff;
  display: flex;
  flex-direction: column;
  font-family: "思源黑体", "Roboto", sans-serif;
}

.statisticsFormBox.show {
  left: 0;
  box-shadow: 0 0 30px rgba(0, 0, 0, 0.5);
}

.content-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
}

.title {
  text-align: center;
  margin-bottom: 20px;
  font-size: 20px;
  font-weight: bold;
  color: #fff;
  position: sticky;
  top: 0;
  z-index: 1;
  padding: 10px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.action-btn {
  padding: 8px 12px;
  margin: 0;
  font-size: 14px;
  border-radius: 4px;
  background-color: #1A3A6F;
  border: 1px solid #005BAA;
  color: #fff;
  transition: all 0.3s ease;
  font-weight: 500;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.action-btn:hover {
  background-color: #005BAA;
  border-color: #1A3A6F;
  color: #fff;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.action-btn:active {
  transform: translateY(1px);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.FormBox {
  display: flex;
  flex-direction: row;
  flex: 1;
  gap: 20px;
  min-height: 0;
  margin-top: 10px;
  overflow-y: auto;
  overflow-x: hidden;
  padding-bottom: 20px;
  height: calc(100vh - 100px);
}

.box1 {
  display: flex;
  flex-direction: column;
  min-height: 0;
  gap: 20px;
  width: 50%;
}

.index-card {
  background: rgba(19, 32, 57, 0.7);
  border-radius: 10px;
  color: #fff;
  margin-bottom: 0;
  border: none;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
  position: relative;
  overflow: visible !important;
  transition: all 0.3s ease;
  flex: 1;
  min-height: 150px;
  display: flex;
  flex-direction: column;
}

.index-card:first-child {
  flex: 0.9;
}

.index-card:last-child {
  flex: 1.1;
}

.index-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.index-row {
  margin-bottom: 12px;
}

.index-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 12px 0;
  background: rgba(0, 91, 170, 0.1);
  border-radius: 8px;
  transition: all 0.3s ease;
  height: 100%;
}

.index-item:hover {
  background: rgba(0, 91, 170, 0.2);
}

.index-value {
  font-size: 24px;
  font-weight: bold;
  color: #E1F5FE;
  margin: 4px 0;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
}

.index-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
}

.iconfont {
  font-size: 22px;
  color: #E1F5FE;
  margin-bottom: 4px;
}

.repair-index-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  justify-content: center;
  height: 100%;
  padding: 10px;
}

.repair-index-item {
  text-align: left;
  padding: 8px;
  border-radius: 6px;
  background: rgba(0, 91, 170, 0.1);
  transition: all 0.3s ease;
}

.repair-index-item:hover {
  background: rgba(0, 91, 170, 0.2);
}

.repair-index-value {
  font-size: 22px;
  font-weight: bold;
  color: #E1F5FE;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
}

.repair-index-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
}

.radar-container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: visible !important;
  margin-bottom: 0;
  padding: 5px;
  min-height: 180px;
}

.radar-chart {
  width: 100%;
  height: 100%;
}

.chart-container {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: visible !important;
  margin-top: 10px;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 250px;
}

.chart {
  width: 100%;
  height: 100%;
}

.btn-container {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

/* 自定义滚动条样式 */
.FormBox::-webkit-scrollbar {
  width: 6px;
}

.FormBox::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 3px;
}

.FormBox::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.1);
}

/* 自定义按钮样式 */
:deep(.el-button) {
  background-color: #1A3A6F;
  border: 1px solid #005BAA;
  color: #fff;
  border-radius: 4px;
  transition: all 0.3s ease;
  font-weight: 500;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

:deep(.el-button:hover) {
  background-color: #005BAA;
  border-color: #1A3A6F;
  color: #fff;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

:deep(.el-button:active) {
  transform: translateY(1px);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* 修改 el-card__body 的样式 */
:deep(.el-card__body) {
  padding: 15px;
  overflow: visible !important;
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 日期选择器样式 */
:deep(.el-date-editor) {
  background: rgba(26, 58, 111, 0.3);
  border: 1px solid rgba(0, 91, 170, 0.4);
  border-radius: 4px;
}

:deep(.el-date-editor .el-input__wrapper) {
  background: transparent;
  box-shadow: none !important;
}

:deep(.el-date-editor .el-input__inner) {
  color: #fff;
}

:deep(.el-input__icon) {
  color: rgba(255, 255, 255, 0.7);
}

/* 确保行高度一致 */
.el-row {
  flex: 1;
  display: flex;
}

.el-col {
  display: flex;
  flex-direction: column;
}

/* 占位内容样式 */
.placeholder-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.coming-soon {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  opacity: 0.7;
}

.placeholder-text {
  margin-top: 15px;
  font-size: 16px;
  color: rgba(255, 255, 255, 0.7);
}

/* 移除上面的样式声明后，添加以下内容防止出现样式问题 */
.export-btn,
.close-btn {
  /* 空样式以保持兼容性，防止其他地方引用这些类名 */
}
</style>
